import React, { useState, useEffect } from 'react';
import { Row, Col, Pagination, Empty, Spin } from 'antd';
import ProductCard from './ProductCard';
import { getProducts, Product, ProductQueryParams } from '../../services/product.service';

interface ProductListProps {
  category?: string;
  keyword?: string;
}

const ProductList: React.FC<ProductListProps> = ({ category, keyword }) => {
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState<Product[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(12);

  useEffect(() => {
    fetchProducts();
  }, [category, keyword, page, pageSize]);

  const fetchProducts = async () => {
    try {
      setLoading(true);
      const params: ProductQueryParams = {
        page,
        pageSize,
        category,
        keyword,
      };
      
      const response = await getProducts(params);
      setProducts(response.products);
      setTotal(response.total);
    } catch (error) {
      console.error('Failed to fetch products:', error);
    } finally {
      setLoading(false);
    }
  };

  const handlePageChange = (newPage: number, newPageSize?: number) => {
    setPage(newPage);
    if (newPageSize) {
      setPageSize(newPageSize);
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (products.length === 0) {
    return <Empty description="暂无商品" />;
  }

  return (
    <div>
      <Row gutter={[16, 16]}>
        {products.map((product) => (
          <Col xs={24} sm={12} md={8} lg={6} key={product.id}>
            <ProductCard product={product} />
          </Col>
        ))}
      </Row>
      
      <div style={{ textAlign: 'center', marginTop: 24 }}>
        <Pagination
          current={page}
          pageSize={pageSize}
          total={total}
          onChange={handlePageChange}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 件商品`}
        />
      </div>
    </div>
  );
};

export default ProductList; 